<?php

namespace Lib;

if (! defined ( 'LIB' )) {
	exit ();
}
define ( 'LIB_CONFIG', true );

$_CONFIG = array ();

/**
 *
 * @author ximi
 *        
 */
class Config {
	/**
	 *
	 * @var array
	 */
	private $_aData = array ();

	/**
	 *
	 * @param strint $sFile
	 *        	文件名如果类型是DB时为表明
	 * @param string $sType
	 *        	ini配置文件格式，json为JSON格式，xml为XML格式, DB数据库
	 * @param string $sNode
	 *        	配置文件放入的节点，默认为根节点多级节点用“.”分隔
	 * @return boolean
	 */
	public function init($sFile, $sType = 'json', $sNode = null) {
		global $_CONFIG;
		if (($sType == 'json' || $sType == 'ini' || $sType == 'xml') && is_file ( $sFile )) {
			if ($sType == 'json') {
				$conf = null;
				require_once $sFile;
				$aConf = @json_decode ( $conf, true );
			} elseif ($sType == 'ini') {
				$aConf = @parse_ini_file ( $sFile, true );
			} else {
			}
		} elseif ($sType == 'db') {
		} else {
			$_CONFIG = array();
			return true;
		}
		if ($sNode) {
			$aNode = explode ( '.', $sNode );
			$_conf = &$_CONFIG;
			foreach ( $aNode as $v ) {
				$_conf = &$_conf [$v];
			}
			$_conf = $aConf;
		} else {
			$_CONFIG = $aConf;
		}
		return true;
	}

	public function save($sFile, $sType = 'json', $sNode = null) {
		global $_CONFIG;
		if ($sNode) {
			$aNode = explode ( '.', $sNode );
			$_conf = $_CONFIG;
			foreach ( $aNode as $v ) {
				$_conf = &$_conf [$v];
			}
			$aConf = $_conf;
		} else {
			$aConf = $_CONFIG;
		}
		if ($sType == 'json') {
			$sConf = '<?php' . "\n" . '$conf = \'';
			$sConf .= o ()->Json->format ( $aConf );
			$sConf .= '\';';
			return @file_put_contents ( $sFile, $sConf );
		}
	}

	public function set($sName, $sValue) {
		global $_CONFIG;
		$aName = explode ( '.', $sName );
		$aConf = &$_CONFIG;
		foreach ( $aName as $v ) {
			$aConf = &$aConf [$v];
		}
		$aConf = $sValue;
	}

	public function get($sName = null) {
		global $_CONFIG;
		if ($sName == null) {
			return $_CONFIG;
		} else {
			$aName = explode ( '.', $sName );
			$aValue = $_CONFIG;
			foreach ( $aName as $v ) {
				$aValue = $aValue [$v];
			}
			return $aValue;
		}
	}
}

?>